package bb.lanxing.adapter.team;

import android.content.Context;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

import bb.lanxing.R;
import bb.lanxing.model.database.Event;
import bb.lanxing.util.BitmapHelper;
import bb.lanxing.view.FontTextView;

public class TeamListAdapter extends RecyclerView.Adapter<TeamListAdapter.ViewHolder> {
    private static final int TYPE_ITEM = 1;
    private static final int TYPE_EMPTY = 2;
    private List<Event> mDataList = new ArrayList<>();
    private OnItemClickListener listener;
    private Context mContext;

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView eventCover;
        TextView eventTitle;
        TextView eventAddress;
        ImageView eventDateIcon;
        FontTextView eventDateText;
        FontTextView eventMemberCount;
        FontTextView eventDistance;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            eventCover = itemView.findViewById(R.id.event_cover);
            eventTitle = itemView.findViewById(R.id.event_title);
            eventAddress = itemView.findViewById(R.id.event_address);
            eventDateIcon = itemView.findViewById(R.id.event_date_icon);
            eventDateText = itemView.findViewById(R.id.event_date_text);
            eventMemberCount = itemView.findViewById(R.id.event_member_count);
            eventDistance = itemView.findViewById(R.id.event_distance);
        }
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        mContext = parent.getContext();
        View view;
        if (viewType == TYPE_EMPTY) {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_team_list_empty, parent, false);
        } else {
            view = LayoutInflater.from(mContext).inflate(R.layout.item_team_list, parent, false);
        }
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (mDataList == null || mDataList.size() == 0) {
            return;
        }
        Event event = mDataList.get(position);
        if (event == null) {
            return;
        }
        if (event.getPhotoUrl() != null && !"".equals(event.getPhotoUrl())) {
            String photoUrl = event.getPhotoUrl();
            if (photoUrl.startsWith("[")) {
                try {
                    JSONArray jSONArray = new JSONArray(event.getPhotoUrl());
                    if (jSONArray.length() > 0) {
                        photoUrl = jSONArray.getJSONObject(0).optString("fileUrl");
                    }
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
            if (!"".equals(photoUrl)) {
                Glide.with(mContext).load(photoUrl).dontTransform().into(holder.eventCover);
            }
        }
        holder.eventTitle.setText(makeEventTitle(mContext, event));
        holder.eventAddress.setText(event.getStartAddr());
        long currentTimeMillis = System.currentTimeMillis();
        long startTime = event.getStartTime();
        long endTime = event.getEndTime();
        if (startTime > currentTimeMillis) {
            holder.eventDateIcon.setImageResource(R.drawable.ic_date_green);
            holder.eventDateText.setText(R.string.event_list_date_label_will_begin);
        } else if (endTime <= currentTimeMillis) {
            holder.eventDateIcon.setImageResource(R.drawable.ic_date_grey);
            holder.eventDateText.setText(R.string.event_list_date_label_finish);
        } else {
            holder.eventDateIcon.setImageResource(R.drawable.ic_date_blue);
            holder.eventDateText.setText(R.string.event_list_date_label_doing);
        }
        holder.eventMemberCount.setText(mContext.getString(R.string.event_list_member_num, event.getMemberCount(), event.getMemberLimit()));
        holder.eventDistance.setText(MessageFormat.format("{0,number,#.##} km", event.getDistance()));

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
    }

    private SpannableString makeEventTitle(Context context, Event event) {
        String levelName = Event.getLevelName(context, event.getLevel());
        int levelColor = Event.getLevelColor(event.getLevel());
        SpannableString spannableString = new SpannableString(levelName + event.getTitle());
        spannableString.setSpan(new ImageSpan(context, BitmapHelper.text2Bitmap(levelName, 13.0f, -1, levelColor, 3)), 0, 2, 17);
        return spannableString;
    }

    @Override
    public int getItemCount() {
        if (mDataList != null && mDataList.size() > 0) {
            return mDataList.size();
        } else {
            return 1;
        }
    }

    @Override
    public int getItemViewType(int position) {
        if (mDataList != null && mDataList.size() > 0) {
            return TYPE_ITEM;
        } else {
            return TYPE_EMPTY;
        }
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public void updateData(List<Event> dataList) {
        mDataList = dataList;
        notifyDataSetChanged();
    }
}